<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >
        添加用户
      </el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="210">
        <template slot-scope="{row}">
          <span>{{ row._id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户名" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="昵称" min-width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.nickname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="头像" min-width="80px" align="center">
        <template slot-scope="{row}">
          <el-image :src="row.avatar" fit="scale-down" lazy style="height: 40px" />
        </template>
      </el-table-column>
      <!-- 角色 -->
      <el-table-column label="角色" min-width="150px" align="center">
        <template slot-scope="{row}">
          <el-row>
            <el-button v-for="(item, index) in row.roles" :key="index" size="mini" round>
              {{ getRolesObj[item] }}
            </el-button>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="330" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="70px"
        style="width: 700px; margin-left:50px;"
      >
        <el-form-item label="用户名" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="temp.nickname" />
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            action="https://tt.yinglianzhirong.com/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <!--            {{temp.avatar}}   v-else -->
            <img v-if="temp.avatar" :src="temp.avatar" class="avatar" alt="头像">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
          <!--          <el-input v-model="temp.avatar"/>-->
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="temp.roles" multiple placeholder="请选择角色" style="width:100%">
            <el-option
              v-for="item in roles"
              :key="item._id"
              :label="item.name"
              :value="item._id"
            >
              <span style="float: left">{{ item.name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.desc }}</span>
            </el-option>
          </el-select>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data() {
    return {
      roles: [],
      list: null,
      total: 0,
      listLoading: true,
      temp: {
        _id: '',
        avatar: '',
        name: '',
        nickname: '',
        password: '',
        roles: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '创建用户'
      },
      rules: {
        name: [{ required: true, message: '必须输入用户名', trigger: 'change' }],
        password: [{ required: true, message: '必须输入密码', trigger: 'blur' }]
      }
    }
  },
  computed: {
    getRolesObj: function() {
      const me = this
      const result = {}
      me.roles.forEach(e => {
        result[e._id] = e.name
      })
      return result
    }
  },
  created() {
    this.getTableRecords()
  },
  mounted() {
    this.$api.getRoleListApi().then(response => {
      this.roles = response.data.items
    })
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // 头像上传成功之后的操作

      this.temp.avatar = res
    },
    // 头像上传
    beforeAvatarUpload(file) { // 上传前的函数
      // 上传前对图片类型和大小进行判断
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      // 校验成功上传文件
      if (isJPG && isLt2M === true) {
        // 将文件转化为formdata数据上传
        const fd = new FormData()
        fd.append('file', file)
      }
      return isJPG && isLt2M
    },
    getTableRecords() {
      this.listLoading = true
      this.$api.getUsersListApi().then(response => {
      // getUsers().then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    resetTemp() {
      this.temp = {
        _id: '',
        avatar: '',
        name: '',
        nickname: '',
        password: ''
      }
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$api.createUserApi(this.temp).then(() => {
            this.getTableRecords()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: '用户添加成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          this.$api.updateUserApi(tempData).then(() => {
            // const index = this.list.findIndex(v => v.id === this.temp.id)
            // this.list.splice(index, 1, this.temp)
            this.getTableRecords()
            this.dialogFormVisible = false
            this.$notify({
              title: 'Success',
              message: 'Update Successfully',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row, index) {
      this.$api.deleteUserApi(row).then((data) => {
        this.getTableRecords()
        this.$notify({
          title: data.message,
          message: '',
          type: 'success',
          duration: 2000
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .filter-container {
    //margin-top: 30px;
    margin-bottom: 20px;
  }
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
